<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form
          @submit.native.prevent
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="文章名称" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入文章名称"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="type">
            <el-select v-model="queryParams.checkStatus" placeholder="请选择">
              <el-option
                v-for="dict in article_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="栏目分类" prop="type">
            <el-select v-model="queryParams.articleType" placeholder="请选择">
              <el-option
                v-for="dict in article_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" @click="handleAdd">新建</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" @click="batchCheck">审核</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" @click="batchCancel">撤销</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              >导出</el-button
            >
          </el-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="userList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="文章标题" align="center" prop="title" />
          <el-table-column label="作者" align="center" prop="creatorName" />
          <el-table-column label="栏目状态" align="center" prop="articleType">
            <template #default="scope">
              <dict-tag
                :options="article_type"
                :value="scope.row.articleType"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="发表时间"
            align="center"
            prop="createTime"
            width="170"
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.gmtCreate) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="checkStatus">
            <template #default="scope">
              <dict-tag
                :options="article_status"
                :value="scope.row.checkStatus"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <a
                href="javascript:;"
                style="
                  color: #358de5;
                  text-decoration: none;
                  margin-right: 10px;
                "
                @click="handleLook(scope.row, 1)"
                >查看</a
              >
              <a
                href="javascript:;"
                v-if="scope.row.checkStatus == 'WAIT_CHECK'"
                style="
                  color: #358de5;
                  text-decoration: none;
                  margin-right: 10px;
                "
                @click="handleCheck(scope.row)"
                >审核</a
              >
              <a
                href="javascript:;"
                style="
                  color: #fcb80b;
                  text-decoration: none;
                  margin-right: 10px;
                "
                @click="handleCancel(scope.row)"
                >撤销</a
              >
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form
        @submit.native.prevent
        :model="form"
        :rules="rules"
        ref="userRef"
        label-width="100px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="文章名称" prop="title">
              <el-input
                v-model="form.title"
                placeholder="请输入"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="栏目类型" prop="articleType">
              <el-select v-model="form.articleType" placeholder="请选择">
                <el-option
                  v-for="item in article_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="封面图片" prop="coverImageUrl" required>
              <ImageUpload
                v-model="form.coverImageUrl"
                :materialType="1"
                :fileType="['png', 'jpg', 'jpeg']"
              ></ImageUpload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="banner图片" required>
              <ImageUpload
                v-model="form.imageUrls"
                :materialType="1"
                :limit="2"
                :fileType="['png', 'jpg', 'jpeg']"
                :isPreview="true"
              ></ImageUpload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="图文内容" prop="content" required>
              <Editor v-model="form.content" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer v-if="title !== '详情'">
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
    
    <script setup name="articleManage">
import {
  queryArticlePage,
  addArticle,
  editArticle,
  articleExport,
  articleVerify,
  undoArticle,
} from "@/api/article";
const { proxy } = getCurrentInstance();
const { article_type, article_status } = proxy.useDict(
  "article_type",
  "article_status"
);
const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const data = reactive({
  form: {
    id: undefined,
    title: "",
    coverImageUrl: "",
    imageUrls: [],
    content: "",
    articleType: "",
  },
  queryParams: {
    pageNum: 1,
    pageSize: 1000,
    title: undefined,
    checkStatus: undefined,
    articleType: undefined,
  },
  rules: {
    title: [
      { required: true, message: "文章名称不能为空", trigger: "blur" },
      {
        min: 2,
        max: 20,
        message: "用户名称长度必须介于 2 和 20 之间",
        trigger: "blur",
      },
    ],
    articleType: [{ required: true, message: "文章类型不能为空", trigger: "change" }],
    content: [{ required: true, message: "文章内容不能为空", trigger: "blur" }],
    coverImageUrl: [{ required: true, message: "文章封面不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 选择条数  */
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 查询用户列表 */
const getList = () => {
  loading.value = true;
  queryArticlePage(queryParams.value).then((res) => {
    loading.value = false;
    userList.value = res.rows;
    total.value = Number(res.total);
  });
};
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  queryParams.value = {
    pageNum: 1,
    pageSize: 1000,
    title: undefined,
    checkStatus: undefined,
    articleType: undefined,
  };
  handleQuery();
};

/** 批量审核 */
const batchCheck = async () => {
  if (ids.value.length == 0) {
    proxy.$modal.msgWarning("请选择操作内容");
    return false;
  }
  let result = await articleVerify(ids.value.toString());
  if (result.code == 200) {
    getList();
    proxy.$modal.msgSuccess("操作成功");
  }
};

/** 批量撤销 */
const batchCancel = async () => {
  if (ids.value.length == 0) {
    proxy.$modal.msgWarning("请选择操作内容");
    return false;
  }
  let result = await undoArticle(ids.value.toString());
  if (result.code == 200) {
    getList();
    proxy.$modal.msgSuccess("操作成功");
  }
};

/** 导出按钮操作 */
const handleExport = async () => {
  proxy.$modal.loading("文件导出中，请稍候...");
  let result = await articleExport();
  const blob = new Blob([result]);
  let link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.download = "文章列表_" + new Date().getTime() + ".xlsx";
  link.click();
  proxy.$modal.closeLoading();
};

/** 重置操作表单 */
const reset = () => {
  form.value = {
    id: undefined,
    title: "",
    coverImageUrl: "",
    imageUrls: [],
    content: "",
    articleType: "",
  };
  proxy.resetForm("userRef");
};

const handleAdd = () => {
  title.value = "新增";
  reset();
  open.value = true;
};
/** 取消按钮 */
const cancel = () => {
  open.value = false;
  changeScore.value = false;
  reset();
};

/** 删除按钮操作 */
const handleCancel = (row) => {
  proxy.$modal
    .confirm("是否确认要撤销《" + row.title + "》文章")
    .then(() => {
      return undoArticle(row.id);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("撤销成功");
    })
    .catch(() => {});
};
/** 修改按钮操作 */
const handleLook = (row, type) => {
  reset();
  title.value = type == 1 ? "详情" : "编辑";
  form.value = {
    ...row,
  };
  open.value = true;
};

/** 修改按钮操作 */
const handleCheck = (row) => {
  proxy.$modal
    .confirm("通过该文章《" + row.title+"》审核")
      .then(() => {
      return articleVerify(row.id);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("审核通过");
    })
    .catch(() => {});
};


watch(
    ()=>open.value,
    (val)=>{
      if(val) {
        form.value.imageUrls = JSON.parse(form.value.imageUrls)
      }
    }
)

/** 提交按钮 */
const submitForm = () => {
  proxy.$refs["userRef"].validate((valid) => {
    if (valid) {
      //if (form.value && form.value.id != "") {
      //   editArticle(form.value).then((response) => {
      //     proxy.$modal.msgSuccess("编辑成功");
      //     open.value = false;
      //     getList();
      //   });
      // } else {

      form.value.imageUrls=JSON.stringify(form.value.imageUrls?form.value.imageUrls.split(","):[])
        addArticle(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      //}
    }
  });
};

getList();
</script>
    <style lang='scss' scoped>
</style>
    